/* Nothing interesting here, just testing the arc function...
 * There bunch of points in top left stacked on top of each other...
 * You can drag them around and see what they do I guess...
 */

#include "common/sketchbook.hpp"

constexpr float2 half = float2::one(.5f);

struct point
{
	constexpr static float radius = 14.f;
	constexpr static int count = 4;
};

std::array<float2, point::count> points
{
	float2{20.f, 20.f},
	float2{380.f, 380.f},
	float2{380.f, 20.f},
	float2{20.f, 380.f}
};

float2* dragged_point = nullptr;

bool is_near(float2 point, float2 position);


void start(Program& program)
{

	program.key_up = [&program](scancode code, keycode)
	{
		switch(code)
		{
			case scancode::leftbracket:
			case scancode::c:
				if(pressed(scancode::rctrl) || pressed(scancode::lctrl))
			case scancode::escape:
				program.end();
			break;

			default: break;
		}
	};

	program.mouse_down = [](float2 position, auto)
	{
		for(auto& point : points)
			if(is_near(point, position))
				dragged_point = &point;
	};

	program.mouse_up = [](auto, auto)
	{
		dragged_point = nullptr;
	};

	program.mouse_move = [](auto, float2 motion)
	{
		if(dragged_point)
			(*dragged_point) += motion;
	};

	program.draw_loop = [](auto frame, auto)
	{

		frame.begin_sketch()
			.rectangle(rect{ frame.size })
			.fill(0xffffff_rgb)
		;

		const auto line1 = common::join(points[0], points[1]);
		const auto line2 = common::join(points[2], points[3]);
		const auto p = common::meet(line1, line2);

		geom::loop(frame.size, [&](auto i) {
			constexpr auto denominator = geom::vector(1.f);
			if(std::abs(line1(i.concat(denominator))) < 200.0f)
				frame.begin_sketch().ellipse(rect{float2::one(), i}).fill(0xff0000_rgb);
			if(std::abs(line2(i.concat(denominator))) < 200.0f)
				frame.begin_sketch().ellipse(rect{float2::one(), i}).fill(0x0000ff_rgb);
		});

		frame.begin_sketch()
			.ellipse(rect{float2::one(point::radius), p.xy()/p.z(), half})
			.fill(0xff00ff_rgb);

		{ auto sketch = frame.begin_sketch();
			for(int i = 0; i < point::count; ++i)
				sketch.ellipse(rect{float2::one(point::radius), points[i], half});
			sketch.line_width(1).outline(0x555555_rgb);
		}

	};
}

bool is_near(float2 point, float2 position)
{
	return (point - position).magnitude() < point::radius * point::radius;
}
